<?php
namespace App\Libs\Helper;
class Util
{
	public static function getIP() {
        static $ip;

        if (isset($ip)) {
            return $ip;
        }
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENTIP'])) {
            $ip = $_SERVER['HTTP_CLIENTIP'];
        } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = '127.0.0.1';
        }
        $pos = strpos($ip, '|');
        if ($pos) {
            $ip = substr($ip, 0, $pos);
        }
        $ip = trim($ip);

        return $ip;
    }
	
	public static function getOS() {
		return \Phalcon\DI::getDefault()->get('request')->get('os');
	}

	public static function getVersion() {
		return \Phalcon\DI::getDefault()->get('request')->get('version');
	}

    public static function getCurl($url, $backDataInfo = false)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        if ($backDataInfo) {
            $info = curl_getinfo($ch);
            curl_close($ch);

            return ['result' => $result, 'info' => $info];
        }
        curl_close($ch);
        return $result;
    }


    //CURLOPT_POSTFIELDS,在没有上传文件时，使用http_build_query，上传文件时，不需要；
    public static function postCurl($url, $data, $haveFile = false, $backDataInfo = false)
    {
        $ch = curl_init();
        if ($haveFile || is_string($data)) {
            $finalData = $data;
        } else {
            $finalData = http_build_query($data);
        }
        if (!strpos($url, 'https://') === FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $finalData);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        if ($backDataInfo) {
            $info = curl_getinfo($ch);
            curl_close($ch);
            return ['result' => $result, 'info' => $info];
        }
        curl_close($ch);
        return $result;
    }
}
